//
//  TestViewController.m
//  Village
//
//  Created by 程虎 on 2017/9/11.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "PostedViewController.h"
#import "TZPhotoScrollView.h"
#import "PostedTools.h"
#import "PostedType.h"

@interface PostedViewController ()<UITextViewDelegate,UITextFieldDelegate>
{
    int forr;
}
@property (nonatomic, strong) NSMutableArray *photoAry;
@property (nonatomic, strong) TZPhotoScrollView *photoScollView;
@property (nonatomic, strong) LocationTools *locationTools;
@property (nonatomic, strong) PostedType *model;
@property (nonatomic, assign) NSInteger IMGindex;
@property (nonatomic, strong) NSArray *imgAry;
@property (nonatomic, assign) BOOL isLocation;
@property (nonatomic, assign) BOOL isFailure; //图片失败

@end

@implementation PostedViewController

- (void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    self.model = (PostedType *)obj;
    LSLog(@"name ----  %@",self.model.name3);
    LSLog(@"code ----  %@",self.model.code3);
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发头条";
    self.view.backgroundColor = kBackgroundColor;
    self.isLocation = NO;
    self.isFailure = NO;

    [self set_NavItem];
    
    [self config_UI];
}

#pragma mark - 设置导航栏左右按钮
- (void)set_NavItem
{
    UIButton *leftbtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,70,40)];
    [leftbtn setTitle:@"取消" forState:UIControlStateNormal];
    leftbtn.titleLabel.font = LRFont(15);
    leftbtn.titleEdgeInsets = UIEdgeInsetsMake(5, -40, 5, 0);
    [leftbtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:leftbtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *rightbtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,70,40)];
    [rightbtn setTitle:@"发布" forState:UIControlStateNormal];
    rightbtn.titleLabel.font = LRFont(15);
    rightbtn.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, -40);
    [rightbtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightbtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)config_UI
{
    WeakSelf(weakSelf);
    self.IMGindex = 0;
    self.photoScollView = [[TZPhotoScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W - 31, 70) ShowVC:self];
    self.photoScollView.maxCountTF = 3;
    self.photoScollView.columnNumberTF = 3;
   
    self.photoScollView.photoScrollBlcok = ^(NSArray *array) {
        weakSelf.IMGindex = array.count;
        weakSelf.imgAry = array;
        if (array.count) {
            [weakSelf uploadImage:array];
        }
    };
    
    self.photoScollView.photoScrollBlcok1 = ^(NSArray *array) {
        weakSelf.IMGindex = array.count;
        weakSelf.imgAry = array;
        if (array.count) {
            [weakSelf uploadImage1:array];
        }
    };
    
    [self.takePicView addSubview:self.photoScollView];
    self.titlefiled.delegate = self;
    self.contentView.delegate = self;
    
    [self.titlefiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self startLocation];
}


#pragma mark - 设置
- (void)leftBtnClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 发布
- (void)rightBtnClick
{
    if (self.isLocation) {
        [self postedNews];
    }
    else {
        [self startLocation];
        [MBProgressHUD showError:@"正在获取当前位置信息，请稍候！" toView:self.navigationController.view];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.contentHolder.hidden = textView.hasText;
}

#pragma mark - 发布文章
-(void)postedNews
{
    if (!self.titlefiled.text.length) {
        [MBProgressHUD showError:@"请输入标题！" toView:self.navigationController.view];
    }
    else if (!self.contentView.text.length) {
        [MBProgressHUD showError:@"请输入头条内容！" toView:self.navigationController.view];
    }else if (self.contentView.text.length>200){
         [MBProgressHUD showError:@"内容字数不能超过200！" toView:self.navigationController.view];
    }
    else{
        
        
        if (self.isFailure) {
            [self uploadImage:self.imgAry];
        }
        else if (self.IMGindex != self.photoAry.count) {
            self.isFailure = YES;
            [MBProgressHUD showError:@"图片上传失败！" toView:self.navigationController.view];
        
        }else
        {
            [self uploadNews];
        }

    }
}

#pragma mark - 定位
- (void)startLocation
{
    [[PermissionManager getPermissionManager] requestLocationPermissionBlock:^(BOOL b) {
    }];
    self.locationTools = [[LocationTools alloc] init];
    [self.locationTools startLocation];
    WeakSelf(weakSelf);
    self.locationTools.locationBlock = ^(LocationModel *model) {
        if (model != nil) {
            weakSelf.isLocation = YES;
            weakSelf.addressLab.text = [NSString stringWithFormat:@"地点/%@",model.address];
//            weakSelf.addressLab.text = @"恩菲尔共同入股任天野好友推荐还风儿哥哥突然回头如何有她风热个丰台共同";
        }
        else {
            weakSelf.isLocation = NO;
        }
    };
}

#pragma mark - 上传发布信息
- (void)uploadNews
{
    WeakSelf(weakSelf);
    if (!self.isFailure) {
        [MBProgressHUD showMessage:@"正在上传..." toView:self.navigationController.view];
    }
    
    [PostedTools GetPostedNewsWithTitle:self.titlefiled.text WithContents:self.contentView.text WithAddress:self.addressLab.text WithType:self.model.code3 Photo:[Tools toJSONString:self.photoAry] Success:^(NSArray *valueAry) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showSuccess:@"发布成功！" toView:self.navigationController.view Completion:^{
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showError:error toView:self.navigationController.view];
    }];
}

#pragma mark - 上传图片
- (void)uploadImage:(NSArray *)array
{
    //=================基于LEAP的文件上传操作=================
    if (!self.isFailure) {
        [MBProgressHUD showMessage:@"正在加载..." toView:self.navigationController.view];
    }
    else {
        [MBProgressHUD showMessage:@"正在上传..." toView:self.navigationController.view];
    }
    [PostedTools UploadImgsWithIMGArys:array Success:^(NSArray *valueAry) {
        if (!self.isFailure) {
            [MBProgressHUD hideHUDForView:self.navigationController.view];
        }
    [MBProgressHUD hideHUDForView:self.navigationController.view];
        
        self.isFailure = NO;
        self.photoAry = [NSMutableArray arrayWithArray:valueAry];
        if (self.isFailure) {
            self.isFailure = NO;
            [self uploadNews];
        }
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showError:error toView:self.navigationController.view];
        self.isFailure = YES;
 
    }];
}
#pragma mark - 删除重新上传图片
- (void)uploadImage1:(NSArray *)array
{
    //=================基于LEAP的文件上传操作=================
    
    [MBProgressHUD showMessage:@"正在删除..." toView:self.navigationController.view];
    
    [PostedTools  UploadImgsWithIMGArys:array Success:^(NSArray *valueAry) {
        if (!self.isFailure) {
            [MBProgressHUD hideHUDForView:self.navigationController.view];
        }
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        self.isFailure = NO;
        self.photoAry = [NSMutableArray arrayWithArray:valueAry];
        if (self.isFailure) {
            self.isFailure = NO;
            [self uploadNews];
        }
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showError:error toView:self.navigationController.view];
        self.isFailure = YES;
        
    }];
}

#pragma mark - title 限制字
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.titlefiled) {
        if (textField.text.length > 20) {
            UITextRange *markedRange = [textField markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:20];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
}

@end


